import { fetchResource } from '../utils/fetchResource'
// import { performScriptForEval } from "../sandbox/performScript";

// 加载html的方法
export const loadHtml = async (app: any) => {
    // 第一个，子应用需要显示在哪里
    let container = app.container // #id 内容
    // 子应用的入口
    let entry = app.entry

    const [dom, scripts] = await parseHtml(entry)

    const ct = document.querySelector(container)
    if (!ct) {
        throw new Error('容器不存在, 请查看')
    }
    console.log('doc',dom)
    ct.innerHTML = dom
    scripts.forEach((item: any) => {
        // performScriptForEval(item)
    });
    return app;
}
export const parseHtml = async (entry: any) => {
    const html = await fetchResource(entry)

    let allScript = [];
    const div = document.createElement('div');
    div.innerHTML = html;

    const [dom, scriptUrl, script] = await getResources(div, entry)

    const fetchedScripts = await Promise.all(scriptUrl.map(async (item: any) => fetchResource(item)))

    allScript = script.concat(fetchedScripts)

    return [dom, allScript]
}

const getResources = async (root: any, entry: any) => {
    const scriptUrl: any = []; // js 链接 src href
    const script: any = []; // 卸载script的JS脚本内容
    const dom = root.outerHTML;

    // 深度解析
    function deepParse(element: any) {
        const children = element.children
        const parent = element.parent;

        // 第一步处理位于 script 中的内容
        if (element.nodeName.toLowerCase() === 'script') {
            const src = element.getAttribute('src');
            // 如果说非src
            if (!src) {
                script.push(element.outerHTML)
            } else {
                // 资源外部链接引入的
                if (src.startsWith('http')) {
                    scriptUrl.push(src)
                } else {
                    // scriptUrl.push(`http:${entry}/${src}`)
                }
            }

            if (parent) {
                parent.replaceChild(document.createComment('此js文件已经被微前端替换'), element)
            }
        }

        // link 也会有js的内容
        if (element.nodeName.toLowerCase() === 'link') {
            const href = element.getAttribute('href');

            if (href.endsWith('.js')) {
                if (href.startsWith('http')) {
                    scriptUrl.push(href)
                } else {
                    scriptUrl.push(`http:${entry}/${href}`)
                }
            }
        }

        for (let i = 0; i < children.length; i++) {
            deepParse(children[i])
        }
    }

    deepParse(root)
    return [dom, scriptUrl, script]
}
